package HashBuck;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2024-02-08
 * Time: 11:55
 */

/**
 * key value 引用结构的哈希桶
 */
public class HashKV<K, V> {
    static class Node<K, V> {
        private K key;
        private V value;

        private Node<K, V> next;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    private Node<K, V>[] array;//哈希数组
    private int useSize;

    private static final float Default_Load_Factor = 0.75f;  // 默认的负载因子

    public HashKV() {
        array = (Node<K, V>[]) new Node[10];
    }

    public void put(K key, V value) {
        // 计算一下 index，引用类型要重写 hascode方法
        int hash = key.hashCode();
        int index = hash % array.length;
        // 查看数组中是否含有 key，如果含有就更新 value值，没有就头插到数组中
        Node<K, V> cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.value = value;
            }
            cur = cur.next;
        }
        // 此时没有找到key值，直接到对应的下标位置进行头插
        Node<K, V> node = new Node(key, value);
        node.next = array[index];
        array[index] = node;
        useSize++;
    }

    public V getValue(K key) {
        // 根据key获取一下value
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K, V> cur = array[index];//找到对应的下标
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.value;
            }
            cur = cur.next;
        }
        return null;
    }
}
